package com.example.gulimall.common.handler;

import com.example.gulimall.common.enums.ServiceCodeEnum;
import com.example.gulimall.common.exceptions.ValidateException;
import com.example.gulimall.common.utils.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>@description: 失败处理器  </p>
 * <p>@author: JGD </p>
 * <p>@create: 2020/2/24 15:42 </p>
 * <p>@version : 2.0.0
 **/
@Slf4j
@Component
public class AuthenticationFailHandler extends SimpleUrlAuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {

        // 默认情况下，不管你是用户名不存在，密码错误，SS 都会报出 Bad credentials 异常信息
        if (e instanceof UsernameNotFoundException || e instanceof BadCredentialsException) {
            log.error("用户名或密码错误");
            ResponseUtil.out(response, ResponseUtil.resultMap(ServiceCodeEnum.SERVER_INTERNAL_ERROR.getCode(), "用户名或密码错误"));
        } else if (e instanceof DisabledException) {
            log.error("账户被禁用，请联系管理员");
            ResponseUtil.out(response, ResponseUtil.resultMap(ServiceCodeEnum.SERVER_INTERNAL_ERROR.getCode(), "账户被禁用，请联系管理员"));
        } else if (e instanceof ValidateException) {
            log.error(e.getMessage());
            ResponseUtil.out(response, ResponseUtil.resultMap(ServiceCodeEnum.SERVER_INTERNAL_ERROR.getCode(), e.getMessage()));
        } else {
            log.error("登录失败，其他内部错误");
            ResponseUtil.out(response, ResponseUtil.resultMap(ServiceCodeEnum.SERVER_INTERNAL_ERROR.getCode(), "登录失败，其他内部错误"));
        }
    }

}